<template>
  <div class="patient-container">
    <!-- 表格区域 -->
    <el-table 
      :data="tableData" 
      border 
      style="width: 100%" 
      v-loading="loading"
      element-loading-text="加载中..."
      :empty-text="errorMessage || '暂无数据'"
      stripe
      highlight-current-row
      class="patient-table">
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="name" label="患者姓名" min-width="100" show-overflow-tooltip>
        <template #default="scope">
          <div class="name-cell">
            <el-avatar :size="24" :src="scope.row.avatar" class="avatar">{{ scope.row.name?.substring(0,1) }}</el-avatar>
            <span class="patient-name">{{ scope.row.name }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="sex" label="性别" width="70" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.sex === '男' ? 'primary' : 'danger'" size="small" effect="plain">
            {{ scope.row.sex }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="age" label="年龄" width="70" align="center">
        <template #default="scope">
          <span class="age-value">{{ scope.row.age }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="idNo" label="身份证号" min-width="180" show-overflow-tooltip>
        <template #default="scope">
          <el-tooltip :content="scope.row.idNo" placement="top" :hide-after="1500">
            <div class="id-cell">
              {{ formatIDCard(scope.row.idNo) }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="officeCode" label="科室" min-width="120" show-overflow-tooltip>
        <template #default="scope">
          <el-tag size="small" effect="plain" class="office-tag">{{ scope.row.officeCode }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="wardAreaCode" label="病区" min-width="120" show-overflow-tooltip>
        <template #default="scope">
          <div class="ward-area-container">
            <el-tooltip 
              :content="`病区编号: ${scope.row.wardAreaCode}`" 
              placement="top"
              :show-after="300">
              <div class="ward-area-card" :class="getWardAreaClass(scope.row.wardAreaCode)">
                <el-icon class="ward-icon"><Location /></el-icon>
                <span class="ward-text">{{ scope.row.wardAreaCode }}</span>=
              </div>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="nursingUnit" label="护理单元" min-width="120" show-overflow-tooltip>
        <template #default="scope">
          <div class="nursing-unit-container">
            <el-tooltip 
              :content="`护理单元: ${scope.row.nursingUnit || '未分配'}`" 
              placement="top"
              :show-after="300">
              <div class="nursing-unit-card">
                <el-icon class="nursing-icon"><FirstAidKit /></el-icon>
                <span class="nursing-text">{{ scope.row.nursingUnit || '未分配' }}</span>
                <el-icon v-if="isSpecialCare(scope.row.nursingUnit)" class="special-care"><Star /></el-icon>
              </div>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="wardCode" label="病房" width="120" align="center">
        <template #default="scope">
          <el-popover
            placement="top"
            :width="220"
            trigger="hover"
            :show-after="300"
            :hide-after="100">
            <template #default>
              <div class="ward-info-popover">
                <p><strong>病房号:</strong> {{ scope.row.wardCode }}</p>
                <p><strong>容纳床位:</strong> {{ getWardCapacity(scope.row.wardCode) }}</p>
                <p><strong>当前状态:</strong> <span :class="getWardStatusClass(scope.row.wardCode)">{{ getWardStatus(scope.row.wardCode) }}</span></p>
              </div>
            </template>
            <template #reference>
              <div class="ward-code-container">
                <div class="ward-code-badge">
                  <span class="ward-number">{{ scope.row.wardCode }}</span>
                  <div class="ward-status-indicator" :class="getWardStatusClass(scope.row.wardCode)"></div>
                </div>
              </div>
            </template>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="bedCode" label="床位号" width="120" align="center">
        <template #default="scope">
          <div class="bed-cell-large">
            <el-tooltip :content="`床位: ${scope.row.bedCode}`" placement="top">
              <div class="bed-icon-container">
                <el-icon class="bed-icon"><Van /></el-icon>
                <span class="bed-number-large">{{ scope.row.bedCode }}</span>
              </div>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <div class="action-buttons">
            <el-button type="primary" size="small" @click="openupd(scope.row.patientCode)">
              <el-icon><Edit /></el-icon>编辑
            </el-button>
            <el-button type="info" size="small" @click="viewDetails(scope.row)">
              <el-icon><View /></el-icon>查看
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageing.index"
        v-model:page-size="pageing.size"
        :page-sizes="[2, 4,6, 10]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageing.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, reactive, ref, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { Edit, View, Location, FirstAidKit, Star, Van } from '@element-plus/icons-vue'

const { proxy } = getCurrentInstance()
const router = useRouter()

// 状态定义
const loading = ref(false)
const errorMessage = ref('')
const tableData = ref([])

// 分页配置
const pageing = reactive({
  index: 1,
  size: 4,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  name: '',
  idNo: ''
})

// 监听分页变化
watch(
  () => [pageing.index, pageing.size],
  () => {
    getTableData()
  }
)

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  errorMessage.value = ''
  
  try {
    const params = new URLSearchParams()
    params.append('pageIndex', pageing.index)
    params.append('pageSize', pageing.size)
    
    // 添加搜索条件
    if (searchForm.name) params.append('name', searchForm.name)
    if (searchForm.idNo) params.append('idNo', searchForm.idNo)
    
    const url = `api/EquipmentController/GetPatient?${params.toString()}`
    const res = await proxy.http.get(url)
    
    if (res.data) {
      tableData.value = res.data.rows || []
      pageing.total = res.data.total || 0
    } else {
      errorMessage.value = '获取数据失败'
      tableData.value = []
    }
  } catch (error) {
    console.error('获取患者列表失败:', error)
    errorMessage.value = '获取数据失败，请稍后重试'
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 跳转到编辑页面
const openupd = (patientCode) => {
  router.push({
    path: '/patientedit',
    query: { patientCode }
  })
}

// 查看患者详情
const viewDetails = (patient) => {
  ElMessageBox.alert(
    `<div>
      <p><strong>患者姓名:</strong> ${patient.name}</p>
      <p><strong>身份证号:</strong> ${patient.idNo}</p>
      <p><strong>性别:</strong> ${patient.sex}</p>
      <p><strong>年龄:</strong> ${patient.age}</p>
      <p><strong>科室:</strong> ${patient.officeCode}</p>
      <p><strong>病区:</strong> ${patient.wardAreaCode}</p>
    </div>`,
    '患者详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭'
    }
  )
}

// 搜索处理
const handleSearch = () => {
  pageing.index = 1
  getTableData()
}

// 重置搜索条件
const resetSearch = () => {
  searchForm.name = ''
  searchForm.idNo = ''
  pageing.index = 1
  getTableData()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageing.size = size
  pageing.index = 1
}

// 页码变化
const handleCurrentChange = (page) => {
  pageing.index = page
}

// 页面加载时获取数据
onMounted(() => {
  getTableData()
})

// 格式化身份证号码，保留前四位和后四位
const formatIDCard = (idNo) => {
  if (!idNo) return '';
  if (idNo.length <= 8) return idNo;
  return idNo.substring(0, 4) + '**********' + idNo.substring(idNo.length - 4);
}

// 获取病区分类
const getWardAreaClass = (wardAreaCode) => {
  if (!wardAreaCode) return '';
  
  // 根据病区编号首字母判断类型
  const firstChar = wardAreaCode.charAt(0).toUpperCase();
  
  const classMap = {
    'A': 'ward-area-general', // 普通病区
    'B': 'ward-area-intensive', // 重症病区
    'C': 'ward-area-emergency', // 急诊病区
    'D': 'ward-area-maternity', // 产科病区
    'E': 'ward-area-pediatric', // 儿科病区
    'S': 'ward-area-special', // 特殊病区
  };
  
  return classMap[firstChar] || 'ward-area-other';
};

// 获取病房状态
const getWardStatus = (wardCode) => {
  if (!wardCode) return '未知';
  
  // 模拟不同病房状态
  const lastDigit = parseInt(wardCode.toString().slice(-1));
  
  const statusMap = {
    0: '已满',
    1: '已满',
    2: '有空余',
    3: '有空余',
    4: '有空余',
    5: '即将满员',
    6: '即将满员',
    7: '即将满员',
    8: '接近空闲',
    9: '接近空闲'
  };
  
  return statusMap[lastDigit] || '未知';
};

// 获取病房状态对应的样式类
const getWardStatusClass = (wardCode) => {
  if (!wardCode) return '';
  
  const status = getWardStatus(wardCode);
  
  const classMap = {
    '已满': 'ward-status-full',
    '有空余': 'ward-status-available',
    '即将满员': 'ward-status-nearly-full',
    '接近空闲': 'ward-status-mostly-empty',
    '未知': ''
  };
  
  return classMap[status] || '';
};

// 获取病房容量
const getWardCapacity = (wardCode) => {
  if (!wardCode) return '未知';
  
  // 模拟病房容量计算
  const wardNumber = parseInt(wardCode.toString());
  
  // 根据病房号的数字特征来模拟不同的容量
  if (wardNumber < 100) {
    return '2人间';
  } else if (wardNumber < 200) {
    return '4人间';
  } else if (wardNumber < 300) {
    return '6人间';
  } else {
    return '单人间';
  }
};

// 判断是否为特殊护理单元
const isSpecialCare = (nursingUnit) => {
  if (!nursingUnit) return false;
  
  // 特殊护理单元标识
  const specialUnits = ['ICU', 'CCU', 'NICU', 'PICU', 'HDU', '特护'];
  
  return specialUnits.some(unit => nursingUnit.includes(unit));
};
</script>

<style scoped>
.patient-container {
  padding: 20px;
}

.search-area {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.patient-table {
  border-radius: 4px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.patient-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}

.patient-table :deep(.el-table__row:hover) {
  background-color: #ecf5ff !important;
}

.name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.patient-name {
  font-weight: 500;
}

.avatar {
  background-color: #409eff;
  color: white;
  font-size: 12px;
}

.id-cell {
  font-family: monospace;
  letter-spacing: 1px;
}

.office-tag {
  border-radius: 12px;
}

.ward-area-container, .nursing-unit-container {
  display: flex;
  align-items: center;
}

.ward-area-card, .nursing-unit-card {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 13px;
  background-color: #f5f7fa;
  cursor: pointer;
  transition: all 0.2s ease;
}

.ward-area-card:hover, .nursing-unit-card:hover {
  background-color: #ebeef5;
}

.ward-text, .nursing-text {
  font-weight: 500;
}

.ward-icon, .nursing-icon {
  font-size: 14px;
  color: #409eff;
}

.special-care {
  color: #e6a23c;
  margin-left: 2px;
}

/* 病区类型样式 */
.ward-area-general {
  background-color: #e1f3ff;
}

.ward-area-intensive {
  background-color: #ffe1e1;
}

.ward-area-emergency {
  background-color: #fff3e0;
}

.ward-area-maternity {
  background-color: #f5e0ff;
}

.ward-area-pediatric {
  background-color: #e0ffef;
}

.ward-area-special {
  background-color: #f0e7ff;
}

.ward-area-other {
  background-color: #f5f7fa;
}

/* 病房状态样式 */
.ward-status-full {
  color: #f56c6c;
  font-weight: bold;
}

.ward-status-available {
  color: #67c23a;
  font-weight: bold;
}

.ward-status-nearly-full {
  color: #e6a23c;
  font-weight: bold;
}

.ward-status-mostly-empty {
  color: #409eff;
  font-weight: bold;
}

/* 病房号样式 */
.ward-code-container {
  display: flex;
  justify-content: center;
}

.ward-code-badge {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  min-width: 80px;
  height: 60px;
  background-color: #f0f9ff;
  border-radius: 6px;
  border: 1px solid #d9ecff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
  cursor: pointer;
}

.ward-code-badge:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.ward-number {
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
}

.ward-status-indicator {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #909399;
}

.ward-status-indicator.ward-status-full {
  background-color: #f56c6c;
}

.ward-status-indicator.ward-status-available {
  background-color: #67c23a;
}

.ward-status-indicator.ward-status-nearly-full {
  background-color: #e6a23c;
}

.ward-status-indicator.ward-status-mostly-empty {
  background-color: #409eff;
}

.ward-info-popover {
  font-size: 13px;
  line-height: 1.5;
}

.ward-info-popover p {
  margin: 5px 0;
}

/* 床位号样式 */
.bed-cell-large {
  display: flex;
  justify-content: center;
  cursor: pointer;
}

.bed-icon-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 70px;
  height: 55px;
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
  border-radius: 6px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.bed-icon-container:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.bed-icon {
  font-size: 18px;
  color: #67c23a;
  margin-bottom: 2px;
}

.bed-number-large {
  font-size: 16px;
  font-weight: bold;
  color: #67c23a;
}

.action-buttons {
  display: flex;
  gap: 5px;
}

.action-buttons .el-button {
  padding: 5px 8px;
}

.action-buttons .el-icon {
  margin-right: 3px;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .patient-container {
    padding: 10px;
  }
  
  .el-form-item {
    margin-bottom: 10px;
  }
}
</style>
